<template>
  <div>
    <el-dialog title="分配组织" :close-on-click-modal="false" :visible.sync="visible" fullscreen center append-to-body>
      <el-button class="miui-dialog-close-btn" @click="visible = false">关闭页面</el-button>
      <el-card style="height: calc(100vh - 135px);overflow: auto;">
        <div class="dialog-main-tree">
          <el-tree ref="orgTree" :data="treeData" :default-checked-keys="checkedKeys" :check-strictly="false" :props="defaultProps"
            class="filter-tree" node-key="id" highlight-current show-checkbox default-expand-all />
        </div>
      </el-card>
      <span slot="footer" class="dialog-footer">
        <el-button type="primary" @click="dataFormSubmit()" v-prevent-re-click>保 存</el-button>
      </span>
    </el-dialog>
  </div>
</template>

<script>
    import {mapGetters} from 'vuex'
    import { updateUserOrg } from '@/api/admin/user'
    import { fetchOrg} from "@/api/admin/org";

    export default {
    data () {
      return {
        visible: false,
        userId: '',
        treeData: [],
        defaultProps: {
          children: "children",
          label: "name"
        },
        checkedKeys: [],
        orgIds: '',

      }
    },
    components:{

    },
    computed: {
      ...mapGetters(['bizData'])
    },
    methods: {
      init(row) {
        this.visible = true

        let list = []
        row.orgList.forEach(item => { list.push(item.id) })
        this.userId = row.id
        this.checkedKeys = list

        this.$nextTick(() => {
          fetchOrg().then(response => {
            this.treeData = response.data.data
            // 解析出所有的太监节点
            this.checkedKeys = this.resolveAllEunuchNodeId(this.treeData, this.checkedKeys, [])
            this.roleId = row.roleId
            this.roleCode = row.roleCode
          })
        })
      },
      /**
       * 解析出所有的太监节点id
       * @param json 待解析的json串
       * @param idArr 原始节点数组
       * @param temp 临时存放节点id的数组
       * @return 太监节点id数组
       */
      resolveAllEunuchNodeId(json, idArr, temp) {
        for (let i = 0; i < json.length; i++) {
          const item = json[i]
          // 存在子节点，递归遍历;不存在子节点，将json的id添加到临时数组中
          if (item.children && item.children.length !== 0) {
            this.resolveAllEunuchNodeId(item.children, idArr, temp)
          } else {
            temp.push(idArr.filter(id => id == item.id))
          }
        }
        return temp
      },
      // 保存阻止分配
      dataFormSubmit() {
        this.orgIds = ''
        this.orgIds = this.$refs.orgTree.getCheckedKeys().join(',').concat(',').concat(this.$refs.orgTree.getHalfCheckedKeys()
          .join(','))
        let data = {
          id: this.userId,
          org: this.orgIds.split(',')
        }
        updateUserOrg(data).then(() => {
          this.visible = false
          this.$notify.success('修改成功')
          this.$emit('refreshDataList')

        })
      }
    }
  }
</script>
